package com.vdongchina.miniapp.http.service;

import com.vdongchina.miniapp.commons.MiniAppException;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Response;

import java.io.IOException;
import java.util.Objects;

/**
 * Copyright (C)
 * FileName: Appservice
 * Author:   maokai
 * Date:     2021/8/12 16:35
 * Description:
 */
public interface IAppService {
    default <T> T parserResult(Call<T> call) throws MiniAppException {
        try {
            Response<T> execute = call.execute();
            int code = execute.code();
            boolean successful = execute.isSuccessful();
            if (code != 200 || !successful) {
                ResponseBody errorBody = execute.errorBody();
                if (Objects.isNull(errorBody)) {
                    String message = execute.message();
                    throw new MiniAppException(message);
                }
                String string = errorBody.string();
                throw new MiniAppException(string);
            }
            T body = execute.body();
            return body;
        } catch (IOException e) {
            e.printStackTrace();
            throw new MiniAppException(e.getMessage());
        }
    }
}
